package org.nativejpa.query;

/**
 * @author <a href="mailto:jfox.young@gmail.com">Young Yang</a>
 * @create 2009-3-25 17:37:16
 */
public class TransactionQuerySynchronization implements QuerySynchronization {

    public void beforeExecuteQuery(SQLQuery query) {
        //TODO: 检查当前是否有事务
        // 如果有但不是当前EntityManager的事务，调用 EntityTransaction.splitTransaction
        if (!query.getEntityManager().getEntityManagerFactory().getEntityManagerFactoryBuilder().isContainerManaged()) {
            query.getEntityManager().suspendTransaction();
        }
    }

    public void beforeExecuteUpdate(SQLQuery query) {
        beforeExecuteQuery(query);
    }

    public void afterExecuteQuery(SQLQuery query, boolean success) {
        if (!query.getEntityManager().getEntityManagerFactory().getEntityManagerFactoryBuilder().isContainerManaged()) {
            query.getEntityManager().resumeTransaction();
        }
    }

    public void afterExecuteUpdate(SQLQuery query, boolean success) {
        afterExecuteQuery(query, success);
    }
}
